<?php
namespace Futures\Controller;
use Futures\Model\OrderModel;
/**
 *  自动更新执行的控制器
 */
class UpdateController{

    /**
     * [updateOpenStatus 早上开盘时执行批量处理，更新当日交易订单的状态和开盘价]
     * @return [type] [description]
     */
    public function updateOpenStatus(){
        //取出等待中的订单
        $orders = M('FuturesOrder')->where(array('status'=>0))->select();
        foreach($orders as $k=>$o){
             //判断时间是否是在当日进行交易
            if(date('Ymd',$o['begin_time'])==date('Ymd')){
                $data = array();
                $data['status'] = 1;
                $res = M('FuturesOrder')->where(array('id'=>$o['id']))->save($data);
                if(false===$res){ 
                    //写入日志
                    $file='./Data/updateorder.txt';
                    $content = date('Ymd His').':更新订单('.$o['id'].')失败;\n';
                    file_put_contents($file,$content, FILE_APPEND);
                }
                //获取合约数据
                //$future = M('Futures')->field('code,type_sign')->find($o['futures_id']);
                //获取实时数据写入开盘
                // $future_data = get_futures_data($future['code'],$future['type_sign']);
                // if(false!==$future_data){
                //     if($future['type_sign']=='commodity'){
                //         $openPrice = $future_data[2];
                //     }elseif($future['type_sign']=='stock'){
                //         $openPrice = $future_data[0];
                //     }
                //     //更改状态和开盘价格
                //     $data = array();
                //     $data['status'] = 1;
                //     $data['open_price'] = $openPrice;
                //     $res = M('FuturesOrder')->where(array('id'=>$o['id']))->save($data);
                //     if(false===$res){ 
                //         //写入日志
                //         $file='./Data/updateorder.txt';
                //         $content = date('Ymd His').':更新订单('.$o['id'].')失败;\n';
                //         file_put_contents($file,$content, FILE_APPEND);
                //     }

                // }
                
            }
        }
    }

    /**
     * [unwind 批量平仓操作]
     * @return [type] [description]
     */
    public function unwind(){ 

        //取出等待中的订单
        $where['status'] = 1;
        $where['close_time'] = 0;
        //$orders = M('FuturesOrder')->where(array('status'=>1))->select();
        $orders = M('FuturesOrder')->where($where)->select();
        foreach($orders as $k=>$o){
             //判断时间是否是在当日进行交易
            if(date('Ymd',$o['end_time'])==date('Ymd')){
            //if(true){    //每天都执行
                $h = date("H");
                $o_h = date('H',$o['end_time']);
                if($h<$o_h){
                    continue;
                }
                
            
                //判断是否达到交易结束时间
                //if(date('Ymd',$o['end_time']>time()) continue;
                //获取合约数据
                $future = M('Futures')->field('code,type_sign,stop_loss,premium')->find($o['futures_id']);
                //获取实时数据写入收盘后最新价
                $future_data = get_futures_data($future['code'],$future['type_sign']);
                if(false!==$future_data){
                    if($future['type_sign']=='commodity'){
                        $closePrice = $future_data[8];
                    }elseif($future['type_sign']=='stock'){
                        $closePrice = $future_data[3];
                    }

                    if($o['direction']==1){
                        //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买涨)
                        //$profit = ($closePrice-$o['open_price'])*$o['number']*$o['premium'];
                        $profit = ($closePrice-$o['open_price']);
                    }elseif($o['direction']==0){
                        //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买跌)
                        //$profit = ($o['open_price']-$closePrice)*$o['number']*$o['premium'];
                        $profit = ($o['open_price']-$closePrice);
                    }elseif($o['direction']==2){
                        //看平分为涨和跌两个方向
                        $ping_d =  $o['open_price']-$closePrice;
                        //如果卖出价大于买入价为涨，计算方式为:买入价*1.01-卖出价
                        ////如果卖出价和买入价相同，计算方式为:买入价*0.01
                        if($ping_d<=0){ //小于0为涨
                            //$profit=$o['open_price']*1.01-$closePrice;
                            $profit=$closePrice-$o['open_price'];
                        }else{ //大于0为跌
                            //如果卖出价小于买入价为跌，计算方式为:卖出价-买入价0.99
                            //$profit=$closePrice-$o['open_price']*0.99;
                            $profit=$o['open_price']-$closePrice;
                        }
                        $profit=$future['premium']*2-$profit;
                        if($profit>0){  //在看平范围以内
                            if($ping_d<=0){
                                $closePrice=$o['open_price']+$future['premium']*2;
                            }else{
                                $closePrice=$o['open_price']-$future['premium']*2;
                            }
                        }
                        
                    }
                    //最大值为权益金的三倍，看平的最大值是权益金的两倍TODO
                    if($o['direction']==1){
                        //盈利最大值
                        // $stop_loss = $future['stop_loss'];
                        // if(strpos($stop_loss,'%')>0){
                        //     $stop_loss = $stop_loss/100;
                        // }
                        // $max_profit = $o['open_price']*$stop_loss;
                        $max_profit = $future['premium']*3;
                        if($profit>$max_profit){
                            $profit = $max_profit;
                            $closePrice=$o['open_price']+$future['premium']*3;
                        }
                    }elseif($o['direction']==0){
                        $max_profit = $future['premium']*3;
                        if($profit>$max_profit){
                            $profit = $max_profit;
                            $closePrice=$o['open_price']-$future['premium']*3;
                        }
                    }
                    
                    $profit = $profit*($o['number']);
                    if($profit<0) $profit=0.00;
                    //更改状态和开盘价格
                    $data['status'] = 2;
                    $data['close_price'] = $closePrice;
                    $data['close_time'] = time();
                    $data['profit'] = $profit;
                    $res = M('FuturesOrder')->where(array('id'=>$o['id']))->save($data);
                    if(false===$res){
                        //写入日志
                        $file='./Data/updateorder.txt';
                        $content = date('Ymd His').':批量平仓(订单'.$o['id'].')失败;\n';
                        file_put_contents($file,$content, FILE_APPEND);
                    }else{
                        $openid = M('Follow')->where(array('id'=>$o['user_id']))->getField('openid');
                        if($profit>0){
                            //获取openid
                            modify_account($openid,$profit,5,'订单（'.$o['id'].'）盈利');
                        }
                        //发送通知
                        $title = "您好，您有一笔交易订单已平仓";
                        // $content = " ";
                        // $content .= "订单号：{$o['transaction_id']}\n";
                        $close_time = date('Y-m-d H:i:s',$data['close_time']);
                        // $content .= "平仓时间：{$close_time}\n";
                        // $content .= "平仓价位：{$data['close_price']}\n";
                        // $content .= "盈利资金：{$profit}\n";
                        // $w_url=U('Transaction/index'); 
                        $direction=array(0=>'买跌',1=>'买涨',2=>'买平');
                        $content=array(
                            'transaction_id'=>$o['transaction_id'],
                            'close_time'=>$close_time,
                            'other'=>$direction[$o['direction']].'('.$o['number'].'张)，盈利'.$profit.'元'
                        );
                        $picurl = $redirect_uri="http://" . $_SERVER['HTTP_HOST'] ."/Public/s4.jpg";
                        send_wx_notify($openid,$title,$content,$w_url,$picurl);
                        
                    }

                }
                
            }
        }
    }


    public function order_unwind($orderid){
        //获取订单信息
        $o = M('FuturesOrder')->where(array('id'=>$orderid,'status'=>1))->find();
         //判断时间是否是在当日进行交易
        if(date('Ymd',$o['begin_time'])==date('Ymd')){
            //判断是否达到交易结束时间
            //if(date('Ymd',$o['end_time']>time()) continue;
            //获取合约数据
            $future = M('Futures')->field('code,type_sign,stop_loss')->find($o['futures_id']);
            //获取实时数据写入收盘后最新价
            $future_data = get_futures_data($future['code'],$future['type_sign']);
            if(false!==$future_data){
                if($future['type_sign']=='commodity'){
                    $closePrice = $future_data[8];
                }elseif($future['type_sign']=='stock'){
                    $closePrice = $future_data[3];
                }

                if($o['direction']==1){
                    //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买涨)
                    //$profit = ($closePrice-$o['open_price'])*$o['number']*$o['premium'];
                    $profit = ($closePrice-$o['open_price']);
                }elseif($o['direction']==0){
                    //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买跌)
                    //$profit = ($o['open_price']-$closePrice)*$o['number']*$o['premium'];
                    $profit = ($o['open_price']-$closePrice);
                }
                //盈利最大值
                $stop_loss = $future['stop_loss'];
                if(strpos($stop_loss,'%')>0){
                    $stop_loss = $stop_loss/100;
                }
                $max_profit = $o['open_price']*$stop_loss;
                if($profit>$max_profit){
                    $profit = $max_profit;
                }
                $profit = $profit*($o['number']);
                if($profit<0) $profit=0.00;
                //更改状态和开盘价格
                //$data['status'] = 2;
                $data['close_price'] = $closePrice;
                $data['close_time'] = time();
                $data['profit'] = $profit;
                $res = M('FuturesOrder')->where(array('id'=>$o['id']))->save($data);
                if(false===$res){
                    //写入日志
                    $file='./Data/updateorder.txt';
                    $content = date('Ymd His').':批量平仓(订单'.$o['id'].')失败';
                    file_put_contents($file,$content, FILE_APPEND);
                }else{
                    $openid = M('Follow')->where(array('id'=>$o['user_id']))->getField('openid');
                    if($profit>0){
                        //获取openid
                        modify_account($openid,$profit,5,'订单（'.$o['id'].'）盈利');
                    }
                    //发送通知
                    $title = "您好，您有一笔交易订单已平仓";
                    $content = " ";
                    $content = "订单号：{$o['transaction_id']}\n";
                    $close_time = date('Y-m-d H:i:s',$data['close_time']);
                    $content .= "平仓时间：{$close_time}\n";
                    $content .= "平仓价位：{$data['close_price']}\n";
                    $content .= "盈利资金：{$profit}\n";
                    $w_url=U('Transaction/index');
                    $picurl = $redirect_uri="http://" . $_SERVER['HTTP_HOST'] ."/Public/s4.jpg";
                    send_wx_notify($openid,$title,$content,$w_url,$picurl);
                    
                }

            }
                
        }
            
        
    }


    public function update_last_price(){
        $future_id = I('fid');  //合约ID
        $future = M('Futures')->field('code,type_sign,stop_loss')->find($future_id);
        //获取实时数据写入收盘后最新价
        $future_data = get_futures_data($future['code'],$future['type_sign']);
        $data =  array();
        if($future['type_sign']=='commodity'){
            $data[2] = $future_data[8]; //最新价
            $data[1] = $future_data[7]; //卖价
            $data[0]  = $future_data[6]; //买价
        }elseif($future['type_sign']=='stock'){
            //dump($future_data);
            $data[2] = $future_data[3];
            $data[1] = $future_data[3]; //卖价
            $data[0]  = $future_data[3]; //买价
        }
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($data));
    }


    public function update_index_orders(){
        
        //先接收传过来的订单id数组
        $orders_id = I('post.ids');
        //查询数组详细信息
        $order_where['id'] = array('in',$orders_id);
        $orders = M('futures_order')->where($order_where)->select();
        //获取每一天订单的最新价并且计算盈利
        foreach($orders as $k=>$o){
             //判断时间是否是在当日进行交易
            //if(date('Ymd',$o['begin_time'])==date('Ymd')){
                //判断是否达到交易结束时间
                $future = M('Futures')->field('code,type_sign,stop_loss,premium')->find($o['futures_id']);
                //获取实时数据写入收盘后最新价
                $future_data = get_futures_data($future['code'],$future['type_sign']);
                if(false!==$future_data){
                    if($future['type_sign']=='commodity'){
                        $closePrice = $future_data[8];
                    }elseif($future['type_sign']=='stock'){
                        $closePrice = $future_data[3];
                    }

                    if($o['direction']==1){
                        //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买涨)
                        //$profit = ($closePrice-$o['open_price'])*$o['number']*$o['premium'];
                        $profit = ($closePrice-$o['open_price']);
                    }elseif($o['direction']==0){
                        //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买跌)
                        //$profit = ($o['open_price']-$closePrice)*$o['number']*$o['premium'];
                        $profit = ($o['open_price']-$closePrice);
                    }elseif($o['direction']==2){
                        //看平分为涨和跌两个方向
                        $ping_d =  $o['open_price']-$closePrice;
                        //如果卖出价大于买入价为涨，计算方式为:买入价*1.01-卖出价
                        ////如果卖出价和买入价相同，计算方式为:买入价*0.01
                        if($ping_d<=0){ //小于0为涨
                            //$profit=$o['open_price']*1.01-$closePrice;
                            $profit=$closePrice-$o['open_price'];
                        }else{ //大于0为跌
                            //如果卖出价小于买入价为跌，计算方式为:卖出价-买入价0.99
                            //$profit=$closePrice-$o['open_price']*0.99;
                            $profit=$o['open_price']-$closePrice;
                        }
                        $profit=$future['premium']*2-$profit;
                        if($profit>0){  //在看平范围以内
                            if($ping_d<=0){
                                $closePrice=$o['open_price']+$future['premium']*2;
                            }else{
                                $closePrice=$o['open_price']-$future['premium']*2;
                            }
                        }
                        
                    }
                    //最大值为权益金的三倍，看平的最大值是权益金的两倍TODO
                    if($o['direction']==1){
                        //盈利最大值
                        // $stop_loss = $future['stop_loss'];
                        // if(strpos($stop_loss,'%')>0){
                        //     $stop_loss = $stop_loss/100;
                        // }
                        // $max_profit = $o['open_price']*$stop_loss;
                        $max_profit = $future['premium']*3;
                        if($profit>$max_profit){
                            $profit = $max_profit;
                            $closePrice=$o['open_price']+$future['premium']*3;
                        }
                    }elseif($o['direction']==0){
                        $max_profit = $future['premium']*3;
                        if($profit>$max_profit){
                            $profit = $max_profit;
                            $closePrice=$o['open_price']-$future['premium']*3;
                        }
                    }
                    
                    $profit = $profit*($o['number']);
                    if($profit<0) $profit=0.00;
                    $orders[$k]['lastprice']=$closePrice;
                    $orders[$k]['lastprofit'] = $profit;                 
                } 
            //}
        }
        //返回
        exit(json_encode($orders));
        //首页订单进行中3条数据
        
    }
}